package com.example.capsule_chat0322.connect;

import android.content.Context;

import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.configuration.ActionType;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.netty.NettyClient;
import com.example.capsule_chat0322.request.RegisterRequest;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author zhuzhiming
 * @Date 2022/5/2 18:50
 */
public class ServerOperation {

    private ThreadPoolExecutor threadPoolExecutor;
    private static NettyClient nettyClient;
    private volatile String isConnect;

    public ServerOperation() {
        nettyClient = NettyClient.getInstance();
    }

    public void connect(Context context) {

        isConnect = System.getProperty("isConnect");
        if (isConnect != null && isConnect.equals("true")) {
            return;
        }
        threadPoolExecutor = GlobalThreadPool.buildThreadPool();
        threadPoolExecutor.execute(() -> {
            try {
                nettyClient.connectServer(context);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }


    public static void connectChatRoom(String roomName) {

        Object userId = GlobalAssistMap.getObject("userId");
        if (userId == null) {
            RegisterRequest.doRegister();
            userId = GlobalAssistMap.getObject("userId");
            if (userId == null) {
                return;
            }
        }

        MessageBean messageBean = new MessageBean();
        messageBean.setActionType(ActionType.CONNECT_TYPE);
        messageBean.setRoomName(roomName);
        messageBean.setSenderId(userId.toString());

        nettyClient.sendMessage(messageBean);

    }


}
